<?php
require '../$header.php';
require '../$enforce_login.php';

function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}
 
$return = array();
$error = false;

$Image = $_FILES['Image']['name'];
$Title = $DB->escape($_POST['Title']);
$X = $DB->escape($_POST['Y']);
$Y = $DB->escape($_POST['X']);

if(!$error)
{
	if(strlen($Title) == 0)
	{
		$return['Error'] = "Please Enter a title";
		$error = true;
	}
	
	if(!$error && strlen($X) == 0)
	{
		$return['Error'] = "Please Enter a X coordinate";
		$error = true;
	}
	
	if(!$error && strlen($Y) == 0)
	{
		$return['Error'] = "Please Enter a Y coordinate";
		$error = true;
	}
}

if(!$error)
{
	if(!$Image)
	{
		$return['Error'] = "No Image Submitted";
		$error = true;
	}
}

if(!$error)
{
	$FileName = stripslashes($_FILES['Image']['name']);
	
 	$Ext = getExtension($FileName);
 	$Ext = strtolower($Ext);
 	
	if (($Ext != "jpg") && ($Ext != "jpeg") && ($Ext != "png") && ($Ext != "gif")) 
	{
		$return['Error'] = "Unknown Extension";
		$error = true;
	}
}

$NewName = "";
if(!$error)
{
	while(file_exists($NewName=date("d_m_Y_i_s")."_".rand(0,10000).'.'.$Ext)){}
	$copied = copy($_FILES['Image']['tmp_name'], "../images/" . $NewName);

	if (!$copied) 
	{
		$return['Error'] = "Could not copy image";
		$error = true;
	}
}

//If no errors registred, print the success message
 if(!$error) 
 {
	$DB->query("
		INSERT INTO spot
		(
			UserID,
			Title,
			Image,
			X,
			Y
		)
		VALUES
		(
			'{$UserID}',
			'{$Title}',
			'{$NewName}',
			'{$X}',
			'{$Y}'
		)
	");
	
	$SpotID = $DB->getInsertID();
	
	$DB->query("SELECT * FROM spot WHERE ID='{$SpotID}' LIMIT 1");
	
	if($DB->num() == 1)
	{
		$fetch = $DB->fetch();
		$return = $fetch;
	}
	else
	{
		$return['Error'] = "Could not find spot!";
	}
 }

echo json_encode($return);

require '../$footer.php';
?>